<template>
  <view class="product-form">
    <!-- 图片上传 -->
    <view class="form-item">
      <view class="label">商品图片</view>
      <view class="upload-box" @click="chooseImage">
        <template v-if="imageUrl">
          <u-image :src="imageUrl" width="160rpx" height="160rpx" radius="8"></u-image>
        </template>
        <template v-else>
          <view class="upload-placeholder">
            <u-icon name="plus" color="#999" size="40"></u-icon>
          </view>
        </template>
      </view>
    </view>
    <view class="containe w100">
      <view class="view form mb-10 flex column justify-center">
        <up-input
          fontSize="32rpx"
          placeholder="请输入品牌名称"
          :border="'bottom'"
          v-model="formData.productName"
          type="text"
        >
          <template #prefix>
            <up-text text="品牌名称" margin="0 16px 0 0" type="tips"></up-text>
          </template>
        </up-input>
        <up-input
          fontSize="32rpx"
          placeholder="请输入款号"
          :border="'bottom'"
          v-model="formData.productCode"
          type="text"
        >
          <template #prefix>
            <up-text text="款号" margin="0 46px 0 0" type="tips"></up-text>
          </template>
        </up-input>
        <up-input
          fontSize="32rpx"
          placeholder="请输入价格"
          :border="'bottom'"
          v-model="formData.price"
          type="text"
        >
          <template #prefix>
            <up-text text="价格" margin="0 46px 0 0" type="tips"></up-text>
          </template>
          <template #suffix>
            <view>元</view>
          </template>
        </up-input>
      </view>
    </view>
    <!-- 库存 -->
    <view class="inventory-item mt-30">
      <view class="labels">{{ shopName }}</view>
      <view class="form-items flex items-center justify-between">
        <view class="label">库存</view>
        <view class="number-input">
          <u-number-box v-model="formData.inStockQuantity" :min="0" :step="1" :buttonSize="28"></u-number-box>
        </view>
      </view>
    </view>

    <!-- 确定按钮 -->
    <view class="bottom-button">
      <button class="confirm-btn" @click="handleSubmit">确定</button>
    </view>

    <!-- 入库成功 -->
    <view class="success-page" v-if="showSuccessPage">
      <view class="success-icon">
        <u-icon name="checkmark-circle" color="rgba(43, 164, 113, 1)" size="80"></u-icon>
      </view>
      <text class="success-text">新建/编辑完成</text>
      <view class="button-group">
        <button class="action-btn secondary-btn" @click="handleComplete">完成</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive } from "vue";
import { getStorage, setStorage } from "@/utils/storage";
import { shopApi } from "@/api";
import { BASE_API } from "@/config";
const shopName = ref("");
let showSuccessPage = ref(false);
const imageUrl = ref("");
const from = ref('')
const formData = reactive({
  productName: "",
  productCode: "",
  productSkuCode:"",
  price: "",
  inStockQuantity: 1
});

onLoad((options) => {
  shopName.value = getStorage("shopName");
  from.value = options.from
  if(options.code) {
    formData.productCode = options.code
  }
});
const chooseImage = () => {
  uni.chooseImage({
    // count: 9,
    // sizeType: ['compressed'],
    // sourceType: ['album', 'camera'],
    success: async (chooseImageRes) => {
      const filePath = chooseImageRes.tempFilePaths[0];

      // 将图片转成二进制数据
      var fileData = wx.getFileSystemManager().readFileSync(filePath);

      // 将二进制数据上传到服务器
      wx.uploadFile({
        url: BASE_API + "/bg/file/upload", // 上传的 URL 地址
        filePath: filePath, // 文件的临时路径
        name: "file", // 服务器端接收文件的字段名
        header: {
          "content-type": "multipart/form-data" // 设置请求头
        },
        formData: {},
        success: function (res) {
          // 上传成功后的操作
          console.log(JSON.parse(res.data));
          imageUrl.value = JSON.parse(res.data).result.url;
        },
        fail: function (res) {
          // 上传失败后的操作
          console.log(res);
        }
      });
    },
    fail: (err) => {
      uni.showToast({
        title: "选择图片失败",
        icon: "none"
      });
    }
  });
};

const handleSubmit = () => {
  // 表单验证
  if (!imageUrl.value && from.value != 'num') {
    uni.showToast({
      title: "请上传商品图片",
      icon: "none"
    });
    return;
  }

  if (!formData.productName || !formData.productCode || !formData.price) {
    uni.showToast({
      title: "请填写完整信息",
      icon: "none"
    });
    return;
  }
  if (formData.inStockQuantity <= 0) {
    uni.showToast({
      title: "库存数量必须大于0",
      icon: "none"
    });
    return;
  }

  let params = {
    image: imageUrl.value,
    ...formData,
    productSkuCode: formData.productCode
  };
  shopApi
    .SHOPSTOCKINSTOCK({
      inStockProducts: [params],
      inStockType: 3
    })
    .then((res) => {
      if (res.code != 200) {
        uni.showToast({
          title: res.errMsg,
          icon: "none"
        });
        return;
      }
      showSuccessPage.value = true;
    });
};
const handleComplete = () => {
   if(from.value == 'num') {
     uni.navigateBack({
       delta: 2
     });
     return
   }
    // TODO: 是否返回到列表页 暂定继续添加
    imageUrl.value = "";
    formData.productName = "";
    formData.productCode = "";
    formData.productSkuCode=""
    formData.price = "";
    formData.inStockQuantity = 1;
    showSuccessPage.value = false;
    // uni.navigateTo({
    //   url: `/pagesshop/inventory/add`
    // });
    uni.navigateBack()
};
</script>
<style lang="scss" scoped>
.product-form {
  background-color: #f3f3f3;
  min-height: 100vh;

  .form-item {
    padding: 30rpx 24rpx;
    box-sizing: border-box;
    background: #fff;
    .label {
      font-size: 28rpx;
      color: #333;
      margin-bottom: 20rpx;
    }

    .upload-box {
      width: 160rpx;
      height: 160rpx;
      background-color: #f5f5f5;
      border-radius: 8rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
    }

    .upload-placeholder {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #f5f5f5;
      border-radius: 8rpx;
    }

    .price-input {
      display: flex;
      align-items: center;

      .unit {
        margin-left: 10rpx;
        color: #333;
        font-size: 28rpx;
      }
    }
  }
  .form-items {
    box-sizing: border-box;
    background: #fff;
    .label {
      font-family: PingFang SC;
      font-size: 14px;
      font-weight: 400;
      line-height: 22px;
      text-align: left;
      text-underline-position: from-font;
      text-decoration-skip-ink: none;
      color: rgba(0, 0, 0, 0.9);
    }
  }
  .containe {
    background: #fff;
  }

  .inventory-item {
    padding: 12rpx 24rpx 24rpx;
    box-sizing: border-box;
    background: #fff;
    .labels {
      font-family: PingFang SC;
      font-size: 12px;
      font-weight: 400;
      line-height: 20px;
      text-align: left;
      text-underline-position: from-font;
      text-decoration-skip-ink: none;
      color: rgba(0, 0, 0, 0.6);
    }
    .number-input {
      margin-top: 20rpx;
    }
  }

  .bottom-button {
    position: fixed;
    bottom: 0rpx;
    left: 0;
    right: 0;
    padding: 24rpx 24rpx 44rpx 24rpx;
    box-sizing: border-box;
    background-color: #fff;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
    box-sizing: border-box;
    z-index: 9;

    .confirm-btn {
      width: 100%;
      height: 80rpx;
      line-height: 80rpx;
      background-color: rgba(214, 142, 68, 1);
      color: #fff;
      border: none;
      border-radius: 40rpx;
      font-size: 32rpx;

      &:active {
        opacity: 0.9;
      }
    }
  }
  .success-page {
    position: fixed;
    top: 0;
    left: 0;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 120rpx 40rpx;
    box-sizing: border-box;
    z-index: 99;
    width: 100%;
    height: 100vh;
    .success-icon {
      margin-bottom: 40rpx;
    }

    .success-text {
      font-size: 36rpx;
      color: #333;
      font-weight: bold;
      margin-bottom: 100rpx;
    }

    .button-group {
      width: 100%;
      display: flex;
      flex-direction: column;
      gap: 20rpx;
      .action-btn {
        width: 100%;
        height: 88rpx;
        line-height: 88rpx;
        border-radius: 44rpx;
        font-size: 32rpx;
        border: none;

        &.primary-btn {
          background-color: rgba(214, 142, 68, 1);
          color: #fff;
        }

        &.secondary-btn {
          background-color: rgba(253, 236, 219, 1);
          color: rgba(214, 142, 68, 1);
        }
      }
    }
  }
}

:deep(.u-input) {
  border-radius: 8rpx;
  padding: 20rpx;
  box-sizing: border-box;
}
</style>
